07. 数学和向量

数学和向量

你在 Python 中做的任何向量数学问题,都可以在 C++ 中使用 for 循环完成。

例 1

你希望用一个常量乘以向量中的每个元素:

#include <iostream>
#include <vector>

using namespace std;

int main() {

    vector<float> example;

    // assign 5 floats with value 10
    example.assign(5,10.0);

    // print out the vector
    for (int i = 0; i < example.size(); i++) {
        cout << example[i] << endl;
    }

    // blank line outputted to terminal
    cout << endl;

    //multiply each value in the vector by 20
    for (int i = 0; i < example.size(); i++) {
        example[i] = 20 * example[i];
    }

    // print out the vector
    for (int i = 0; i < example.size(); i++) {
        cout << example[i] << endl;
    }


    return 0;
}

输出如下所示:

10
10
10
10
10

200
200
200
200
200

例2

或者你可能希望把两个向量加在一起:

#include <iostream>
#include <vector>

using namespace std;

int main() {

    vector<int> exampleone (5);
    vector<int> exampletwo (5);
    vector<int> examplesum (5);

    exampleone[0] = 2;
    exampleone[1] = 6;
    exampleone[2] = 25;
    exampleone[3] = 1;
    exampleone[4] = 18;

    exampletwo[0] = 3;
    exampletwo[1] = 19;
    exampletwo[2] = 8;
    exampletwo[3] = 12;
    exampletwo[4] = 191;

    cout << "vector one ";

    // print out the first vector
    for (int i = 0; i < exampleone.size(); i++) {
        cout << exampleone[i] << " ";
    }

    // create a new line in the terminal
    cout << endl;

    cout << "vector two ";

    // print out the second vector
    for (int i = 0; i < exampletwo.size(); i++) {
        cout << exampletwo[i] << " ";
    }

    // create a new line in the terminal
    cout << endl;

    cout << "vector sum ";

    //add the vectors together
    for (int i = 0; i < exampleone.size(); i++) {
        examplesum[i] = exampleone[i] + exampletwo[i];
    }

    // print out the vector
    for (int i = 0; i < examplesum.size(); i++) {
        cout << examplesum[i] << " ";
    }

    // create a new line in the terminal
    cout << endl;

    return 0;
}

输出如下所示:

vector one 2 6 25 1 18 
vector two 3 19 8 12 191 
vector sum 5 25 33 13 209 

现在你可以使用 C++ 向量来编写程序了!请转到本课程的下一部分,来练习编写向量。